package com.sgcc.pda.mdrh.utils;

import android.content.Intent;
import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.sgcc.pda.baselibrary.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

/**
 * File description.
 *
 * @author 王沛栋
 * @data 2018/5/11 16:58
 */
public class ToolGson2 {

    /**
     * 获取json数据
     *
     * @param jsonString json格式的字符串
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T getBean(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("fm.WorkOrderFragment", e + "");
        }
        return t;
    }

    /**
     * 获取json数据
     *
     * @param jsonString json格式的字符串
     * @param token
     * @param <T>
     * @return
     */
    public static <T> T getBean(String jsonString, TypeToken<T> token) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = (T) gson.fromJson(jsonString, token.getType());
        } catch (Exception e) {
            e.printStackTrace();
            //BaseApplication.mLogger.error("getBean" + e.getMessage());
        }
        return t;
    }

    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }


    public static String getJsonStr(Object obj) {
        String result = null;
        try {
            Gson gson = new Gson();
            result = gson.toJson(obj);
        } catch (Exception e) {
            e.printStackTrace();
            //BaseApplication.mLogger.info("getJsonStr" + e.getMessage());
        }
        return result;
    }

    public static String getJsonStr(Intent intent) {
        Bundle bundle = intent.getExtras();
        JSONObject jsonObject = new JSONObject();
        if (bundle != null) {
            Set<String> set = bundle.keySet();
            try {
                for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                    String key = (String) iterator.next();
                    jsonObject.put(key, bundle.get(key));
                }
            } catch (JSONException e) {
                LogUtil.d(e.getLocalizedMessage());
            }
        }
        return jsonObject.toString();
    }

}
